package com.zeyi.chat.service;

import com.alibaba.fastjson.JSON;
import com.zeyi.chat.dto.Chat;
import com.zeyi.chat.dto.Message;
import com.zeyi.chat.handler.Dispatcher;
import com.zeyi.chat.handler.TaskHandler;
import com.zeyi.chat.manager.SocketManager;
import com.zeyi.chat.mapper.UserMapper;
import com.zeyi.chat.po.User;
import com.zeyi.chat.utils.MybatisUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zeyi
 */
public class UserService {

    private UserService() {
    }

    private static class Singleton {
        public static final UserService INSTANCE = new UserService();
    }

    public static UserService getInstance() {
        return Singleton.INSTANCE;
    }

    /**
     * 通过ID查找用户
     */
    public User getUserById(Integer userId) {
        SqlSession session = MybatisUtil.getSession();
        UserMapper userMapper = session.getMapper(UserMapper.class);
        User user = userMapper.selectByPrimaryKey(userId);
        session.close();
        return user;
    }

    /**
     * 更新用户信息
     */
    public void updateInfo(User user) {
        SqlSession session = MybatisUtil.getSession();
        UserMapper userMapper = session.getMapper(UserMapper.class);
        userMapper.updateByPrimaryKeySelective(user);
        session.commit();
        session.close();
    }

    /**
     * 通过邮箱查找用户
     */
    public User findByEmail(String email) {
        SqlSession session = MybatisUtil.getSession();
        UserMapper userMapper = session.getMapper(UserMapper.class);
        User user = userMapper.findByEmail(email);
        session.close();
        return user;
    }

    /**
     * 注册
     */
    public User register(User user) {
        SqlSession session = MybatisUtil.getSession();
        UserMapper userMapper = session.getMapper(UserMapper.class);
        try {
            userMapper.insert(user);
        } catch (Exception e) {
            return null;
        }
        session.commit();
        session.close();
        return user;
    }

    /**
     * 用户登录
     */
    public User login(User user, Dispatcher dispatcher) {
        SqlSession session = MybatisUtil.getSession();
        UserMapper userMapper = session.getMapper(UserMapper.class);
        User queryUser = userMapper.findByEmail(user.getEmail());
        if (queryUser != null && queryUser.getPassword().equals(DigestUtils.md5Hex(user.getPassword()))) {
            List<Chat> chatList = userMapper.getChatList(queryUser.getId());
            session.close();
            //获取好友id列表
            List<Integer> friendIds = new ArrayList<>();
            chatList.forEach(chat -> {
                if (chat.getCreateId() == null && SocketManager.getSocket(chat.getId()) != null) {
                    chat.setIsOnline(true);
                    friendIds.add(chat.getId());
                } else {
                    chat.setIsOnline(false);
                }
            });
            //上线通知好友
            Runnable task = () -> friendIds.forEach(friendId -> {
                Chat chat = new Chat(queryUser.getId(), queryUser.getAvatar(), true);
                Message message = new Message("ChatHandler/online", JSON.toJSONString(chat));
                SocketManager.send(friendId, message);
            });
            TaskHandler.submit(task);
            queryUser.setChatList(chatList);
            dispatcher.setUserId(queryUser.getId());
            return queryUser;
        } else {
            return null;
        }
    }

    /**
     * 获取朋友id列表
     */
    public List<Integer> getFriendIds(Integer userId) {
        SqlSession session = MybatisUtil.getSession();
        UserMapper userMapper = session.getMapper(UserMapper.class);
        List<Integer> friendIds = userMapper.getFriendIds(userId);
        session.close();
        return friendIds;
    }

    /**
     * 添加好友
     */
    public User addFriend(Integer userId, Integer friendId) {
        SqlSession session = MybatisUtil.getSession();
        UserMapper userMapper = session.getMapper(UserMapper.class);
        Object relation = userMapper.getRelation(userId, friendId);
        if (relation == null) {
            userMapper.addFriend(userId, friendId);
            session.commit();
            User friend = userMapper.selectByPrimaryKey(friendId);
            session.close();
            return friend;
        } else {
            return null;
        }
    }

    /**
     * 删除好友
     */
    public void deleteFriend(Integer userId, Integer friendId) {
        SqlSession session = MybatisUtil.getSession();
        UserMapper userMapper = session.getMapper(UserMapper.class);
        userMapper.deleteFriend(userId, friendId);
        session.commit();
        session.close();
    }
}
